<template>
	<view>
		<view class="poster-wrap flex algin-center justify-center" v-if="posterPopup" @touchmove.prevent.stop @click="closePop">
			<view class="" :style="{marginTop: StatusBar+220+'px'}" v-if="!isDone">
				<!-- <u-loading mode="circle" size="48" ></u-loading> -->
				<text class="text-white">加载中...</text>
			</view>
			<view class="poster-content radius-24" style="height: 420rpx;" :class="isDone ? 'bg-white opacity1' : 'opacity0' ">
				<l-painter css="height: 420rpx;background:#FFFFFF;border-radius:24rpx" ref="painter" @progress="createProgress" @done="createDone" >
					<l-painter-view css="padding:24rpx;border-radius:24rpx;" v-show="isDone">
						<l-painter-view css="color: #222a29;display:flex;align-items:center;height:200rpx">
							<l-painter-image  css="width:150rpx;height:150rpx;object-fit:cover;margin-right:20rpx"
								:src="info.avatar" />
							<l-painter-view
								css="display:flex;flex-direction:column;justify-content:center;align-items:center;">
								<l-painter-text css="font-size:32rpx;font-weight:bold;display: -webkit-box;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width:430rpx;-webkit-line-clamp: 2;" :text="info.name"></l-painter-text>
								<l-painter-text css="font-size:32rpx;margin-top:24rpx;font-weight:bold;display: -webkit-box;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;width:430rpx;-webkit-line-clamp: 2;" :text="info.summary"></l-painter-text>
							</l-painter-view>
						</l-painter-view>
						<!-- 用户信息 start -->
						<l-painter-view
							css="display:flex;justify-content:space-between;align-items:center;width:100%;margin-top:32rpx">
							<!-- 用户信息 -->
							<l-painter-view
								css="display:flex;flex-direction:column;justify-content:space-between;justify-content:center;margin-top:24rpx">
								<l-painter-view css="display:flex;justify-content:center">
									<l-painter-view css="display:flex;flex-direction:column;">
										<l-painter-text :text="info.title" css="font-size:28rpx;color:#000000">
										</l-painter-text>
									</l-painter-view>
								</l-painter-view>
							</l-painter-view>
							<!-- 二维码 -->
							<l-painter-view
								css="display:flex;flex-direction:column;justify-content:center;align-items:center;">
								<l-painter-image :src="info.code" css="width:140rpx;height:140rpx"></l-painter-image>
							</l-painter-view>
						</l-painter-view>
						<!-- 用户信息 end -->
					</l-painter-view>
				</l-painter>
			</view>
			<view class="poster-footer margin-top flex algin-center justify-around" v-show="isDone">
				<button @tap.stop="savePoster">保存至相册</button>
				<button @tap.stop="shareFriends">分享好友</button>
			</view>
		</view>
		</view>
	</view>
</template>

<script>
	/**
	 * @alias 李会超
	 * @description 生成分享海报等功能
	 * @param { Boollean } isShareToMp 是否分享到小程序
	 * */
	import lPainter from './lime-painter/components/l-painter/l-painter.vue';
	import lPainterView from './lime-painter/components/l-painter-view/l-painter-view.vue';
	import lPainterImage from './lime-painter/components/l-painter-image/l-painter-image.vue';
	import lPainterText from './lime-painter/components/l-painter-text/l-painter-text.vue';
	import { IMG_BASE_URL } from '@/common/config.js';
	export default {
		components:{
			lPainter,
			lPainterView,
			lPainterImage,
			lPainterText
		},
		props: {
			info: Object,
			isShareToMp: {
				type: Boolean,
				default: false
			},
			// 是否展示海报
			is_showPoter: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				IMG_BASE_URL:IMG_BASE_URL,
				percent:0,//进度
				isDone:false, //海报是否绘制完毕
				ctx: null,
				previewImageUrl: '',
				
				provider: [], // 已配置的服务供应商
				sharePopup: false,
				posterPopup: false,
				poster: {}
			};
		},
		methods: {
			closePop() {
				this.posterPopup = false
				this.isDone = false
				this.percent = 0
			},
			// 绘制进度
			createProgress(e) {
				let num = (e*100).toFixed(0)
				this.percent = Number(num)
			},
			// 绘制成功事件
			createDone() {
				this.isDone = true
				uni.hideLoading()
			},
			// 图片点击放大
			previewImage(url) {
				uni.previewImage({
					current: url,
					urls: [url]
				});
			},
			savePoster() {
				this.$refs.painter.canvasToTempFilePathSync({
				  fileType: "jpg",
				  // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
				  pathType: 'url',
				  quality: 1,
				  success: (res) => {
				    console.log(res.tempFilePath);
				    // 非H5 保存到相册
				    // H5 提示用户长按图另存
				    uni.saveImageToPhotosAlbum({
				        filePath: res.tempFilePath,
				        success:()=> {
				            this.posterPopup = false
							this.$message.success('保存成功')
				        }
				    });
				  },
				});
			},
			// 打开弹窗
			open() {
				this.posterPopup = true;
			},
			// 关闭弹窗
			close() {
				this.sharePopup = false;
				this.posterPopup = false;
			},
			// 初始化分享数据
			init() {
				this.posterPopup = true;
				this.sharePopup = false;
			},
			// 获取服务商列表
			getProvider() {
				uni.getProvider({
					service: 'share',
					success: data => {
						console.log('已配置的分享服务', data);
						if (this.is_showPoter) {
							this.provider = [...data.provider, 'link', 'image'];
						} else {
							this.provider = [...data.provider, 'link'];
						}
					}
				});
			},
			share(item) {
				this.$util.throttle(() => {
					this.confirm(item);
				}, 2500);
			},
			// 分享好友
			shareFriends() {
				// #ifdef APP-PLUS
				this.$refs.painter.canvasToTempFilePathSync({
				  fileType: "jpg",
				  // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
				  pathType: 'url',
				  quality: 1,
				  success: (res) => {
				    console.log(res.tempFilePath);
					uni.shareWithSystem({
					  type:'image',
					  imageUrl:res.tempFilePath,
					  href: 'https://uniapp.dcloud.io',
					  success(){
					    // 分享完成，请注意此时不一定是成功分享
						this.close();
					  },
					  fail(){
					    // 分享失败
						this.close();
					  }
					})
				  },
				});
				// #endif
				// #ifdef MP-WEIXIN
				this.$refs.painter.canvasToTempFilePathSync({
				  fileType: "jpg",
				  // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
				  pathType: 'url',
				  quality: 1,
				  success: (res) => {
				    console.log(res.tempFilePath);
				    wx.showShareImageMenu({  //分享给朋友
						 path: res.tempFilePath,
						 success: (res) => {
							 console.log("分享成功：", res);
						 },
						 fail: (err) => {
							 console.log("分享取消：", err);
						 },
					})
				  },
				});
				// #endif
			},
			// 分享
			confirm(item) {
				let _scene = '';
				let _provider = item.type;
				let _type = 0;
				switch (_provider) {
					case 'weixin':
						_scene = item.scene;
						uni.share({
							provider: _provider,
							type: _type,
							title: this.info.goodsName,
							scene: _scene,
							summary: this.info.summary,
							href: this.info.href,
							imageUrl: this.info.goodsImage,
							success: res => {
								this.close();
							},
							fail: err => {
								console.log('分享失败', err);
								this.$message.info(global.i18n['分享失败']);
							}
						});
						break;
					case 'forum':
						this.shareForum();
						break;
					case 'qq':
						_type = 1;
						uni.share({
							provider: _provider,
							type: _type,
							title: this.info.goodsName,
							scene: _scene,
							summary: this.info.summary,
							href: this.info.href,
							imageUrl: this.info.goodsImage,
							success: res => {
								this.close();
							},
							fail: err => {
								console.log('分享失败', err);
								this.$message.info(global.i18n['分享失败']);
							}
						});
						break;
					case 'sinaweibo':
						uni.share({
							provider: _provider,
							type: _type,
							title: this.info.goodsName,
							scene: _scene,
							summary: this.info.summary,
							href: this.info.href,
							imageUrl: this.info.goodsImage,
							success: res => {
								this.close();
							},
							fail: err => {
								console.log('分享失败', err);
								this.$message.info(global.i18n['分享失败']);
							}
						});
						break;
					case 'link':
						this.copyLink();
						break;
					case 'image':
						this.createPoster();
						break;
				}
			},
			copyLink() {
				console.log(this.info.href);
				uni.setClipboardData({
					data: this.info.href,
					success: () => {
						this.$message.success(global.i18n['复制成功']);
						this.close();
					}
				});
			},
			// 生成海报
			createPoster() {
				// uni.showLoading({
				// 	title:'加载中...',
				// 	mask:true
				// })
				this.$util.actionAuth(() => {
					this.$emit('getPosterInfo');
				});
			},
			// 初始化画布
			initCanvas() {
				
			},
			// 绘制背景
			drawBack() {
				let ctx = this.ctx;
				ctx.setFillStyle('#FFFFFF');
				ctx.fillRect(0, 0, 375, 550);
				ctx.draw(false, () => {
					console.log('背景绘制成功');
					this.drawUserInfo();
				});
			},
			// 绘制个人信息
			async drawUserInfo() {
				let ctx = this.ctx;
				console.log(this.info);
				await new Promise(resolve => {
					uni.getImageInfo({
						src: this.info.avatar,
						success: res => {
							console.log('头像图片', res);
							let {
								width,
								height,
								path
							} = res;
							let r = width / 2;
							let cx = 20 + r;
							let cy = 20 + r;
							console.log(width, height, cx, cy, r, '=============');
							ctx.arc(cx, cy, r, 0, 2 * Math.PI);
							ctx.clip();
							if (width > height) {
								let startX = (width - height) / 2;
								ctx.drawImage(res.path, startX, 0, height, height, 20, 20, 50, 50);
							} else if (width < height) {
								let startY = (height - width) / 2;
								ctx.drawImage(res.path, 0, startY, width, width, 20, 20, 50, 50);
							} else {
								ctx.drawImage(res.path, 20, 20, 50, 50);
							}

							resolve();
						},
						fail: err => {
							uni.hideLoading();
							this.$message.info(global.i18n['获取头像信息失败']);
							console.log('获取图片信息失败', err);
						}
					});
				});

				ctx.setFillStyle('#333333');
				ctx.setFontSize(18);
				ctx.fillText(this.info.name, 90, 40);
				ctx.setFillStyle(this.$store.state.themeColor);
				ctx.setFontSize(16);
				ctx.fillText(global.i18n['推荐一个好物给你,请查收'], 90, 65);
				ctx.draw(true, () => {
					console.log('个人信息绘制成功');
					this.drawGoodsImage();
				});
			},
			// 绘制商品图片
			async drawGoodsImage() {
				let ctx = this.ctx;
				await new Promise(resolve => {
					uni.getImageInfo({
						src: this.info.goodsImage,
						success: res => {
							console.log('商品图片', res);
							let {
								width,
								height,
								path
							} = res;
							if (width > height) {
								let startX = (width - height) / 2;
								ctx.drawImage(res.path, startX, 0, height, height, 20, 90, 335,
									335);
							} else if (width < height) {
								let startY = (height - width) / 2;
								ctx.drawImage(res.path, 0, startY, width, width, 20, 90, 335, 335);
							} else {
								ctx.drawImage(res.path, 20, 90, 335, 335);
							}

							resolve();
						},
						fail: err => {
							uni.hideLoading();
							console.log('商品图片绘制失败', err);
							this.$message.info(global.i18n['获取商品图片信息失败']);
						}
					});
				});
				ctx.draw(true, () => {
					console.log('商品图片绘制成功');
					this.drawGoodsInfo();
				});
			},
			// 绘制商品名称价格
			drawGoodsInfo() {
				let ctx = this.ctx;
				this.drawText(ctx, this.info.goodsName, 20, 455, 240, 2, '#333333', 18);
				ctx.setFontSize(20);
				ctx.setFillStyle('#FE5014');
				ctx.fillText('￥' + this.info.price, 20, 510);
				ctx.draw(true, () => {
					console.log('商品信息绘制成功');
					this.drawCode();
					// this.exportImage();
				});
			},
			// 绘制二维码
			async drawCode() {
				let ctx = this.ctx;
				await new Promise(resolve => {
					uni.getImageInfo({
						src: this.info.code,
						success: res => {
							console.log('二维码信息', res);
							let {
								width,
								height,
								path
							} = res;
							if (width > height) {
								let startX = (width - height) / 2;
								ctx.drawImage(res.path, startX, 0, height, height, 275, 445, 80,
									80);
							} else if (width < height) {
								let startY = (height - width) / 2;
								ctx.drawImage(res.path, 0, startY, width, width, 275, 445, 80, 80);
							} else {
								ctx.drawImage(res.path, 275, 445, 80, 80);
							}
							resolve();
						},
						fail: err => {
							console.log('二维码绘制失败', err);
							uni.hideLoading();
							this.$message.info(global.i18n['获取二维码信息失败']);
						}
					});
				});
				ctx.draw(true, () => {
					console.log('二维码绘制成功');
					this.exportImage();
				});
			},
			// 导出图片
			exportImage() {
				uni.canvasToTempFilePath({
						canvasId: 'poster-canvas',
						success: res => {
							uni.hideLoading();
							console.log('导出图片成功', res);
							this.previewImageUrl = res.tempFilePath;
						},
						fail: err => {
							uni.hideLoading();
							console.log('导出图片失败', err);
						}
					},
					this
				);
			},
			// 保存图片
			saveImage() {
				uni.saveImageToPhotosAlbum({
					filePath: this.previewImageUrl,
					success: res => {
						console.log(res);
						this.$message.info(global.i18n['保存成功']);
						this.close();
					}
				});
			},
			/**
			 * @description 绘制图片通用方法
			 * @param {Object} ctx - canvas上下文
			 * @param {String} 图片路径 - canvas上下文
			 * */
			async drawImage(ctx, path) {},
			/**
			 * @description 绘制文本通用方法
			 * @param {Object} ctx - canvas上下文
			 * @param {String} text - 文本
			 * @param {Number} startX - X轴开始位置
			 * @param {Number} startY - Y轴开始位置
			 * @param {Number} limitWidth - 文字绘制区限制宽度
			 * @param {Number} limitLine - 文字绘制限制行数
			 * @param {String} color - 文字颜色
			 * @param {Number} size - 字体大小
			 * */
			drawText(ctx, text, startX, startY, limitWidth, limitLine = 2, color = '#333333', size = 18, isBold = false) {
				ctx.setFillStyle(color);
				ctx.setFontSize(size);
				let arrText = text.split('');
				let line = '';
				let column = 0;
				for (let n = 0, len = arrText.length; n < len; n++) {
					let testline = line + arrText[n];
					let metrics = ctx.measureText(testline);
					let testWidth = metrics.width;
					if (testWidth > limitWidth && n > 0 && column < limitLine) {
						ctx.fillText(line, startX, startY);
						column += 1;
						line = arrText[n];
						startY += size * 1.5;
					} else {
						line = testline;
					}
				}
				if (column < limitLine) {
					ctx.fillText(line, startX, startY);
				}
			}
		},
		created() {
			console.log('组件 created');
			this.getProvider();
		}
	};
</script>

<style lang="scss" scoped>
	// .preview-image {
	// 	box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
	// }

	// .offset-canvas {
	// 	position: fixed;
	// 	top: -1000px;
	// 	left: 0;
	// 	z-index: 9999;
	// }
	.progress-box{
		top: 50%;
		transform: translateY(-50%);
	}
	.opacity0{
		opacity: 0;
	}
	.opacity1{
		opacity: 1;
	}
	.poster-wrap{
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		overflow: hidden;
		z-index: 9999999999;
		background: rgba(0, 0, 0, 0.6);
		.poster-content{
			position: absolute;
			z-index: 9999999999;
			transition: all 0.2s ease;
			top: 400rpx;
			left: 24rpx;
			right: 24rpx;
			bottom: 0;
		}
		.poster-footer{
			position: absolute;
			z-index: 9999999999;
			left: 0;
			right: 0;
			top: 858rpx;
			border-radius: 32rpx 32rpx 0;
			button {
				width: 240rpx;
				height: 80rpx;
				line-height: 80rpx;
				border-radius: 40rpx;
				color: #FFFFFF;
				&:nth-child(1){
					background: #FD5353;
				}
				&:nth-child(2){
					background: #325BF5;
				}
				&:after{
					border: none;
				}
			}
		}
	}
	/deep/.fu-drawer-bottom{
		
	}
</style>